import os
import pandas as pd
import time
from datetime import datetime
import sys
sys.path.append('..')
from tjdutils.utils import exists, real_path
from tjdutils.ftp_utils import update_x_pkl
from MYSQL.y_assemble import y_assemble_update

def check_input_x(x_type):
    pth = os.getcwd()
    dir_path = os.path.split(pth)[0]
    input_path = dir_path + os.path.sep + 'input'
    print(input_path)
    exists(input_path)
    if x_type == 'real':
        data_type = 'value'
    else:
        data_type = 'yoy'
    pickle_name = update_x_pkl(data_type=data_type)
    os.chdir(pth)
    pickle_path = real_path(pickle_name)
    data = pd.read_pickle(pickle_path)
    return data, pickle_path


def update_y_xlsx(end_datetime, y_name, y_path):
    Update = y_assemble_update()
    data = Update.select_all_table()
    data.to_excel(y_path)
    print("y_plus_集合.xlsx更新完毕")
    if pd.isnull(data.loc[datetime.strptime(end_datetime[-2], '%Y-%m-%d'), y_name]):
        raise ValueError("数据库找不到所需数据，请修改end_datetime")
    return data

def check_input_y(end_datetime, y_name):
    pth = os.getcwd()
    dir_path = os.path.split(pth)[0]
    input_path = dir_path + os.path.sep + 'input'
    exists(input_path)
    y_path = input_path + '/y_plus_集合.xlsx'
    if os.path.isfile(y_path) == False:
        new_data = update_y_xlsx(end_datetime, y_name, y_path)
    else:
        old_data = pd.read_excel(y_path, index_col=0)
        if pd.isnull(old_data.loc[datetime.strptime(end_datetime[-2], '%Y-%m-%d'), y_name]):
            new_data = update_y_xlsx(end_datetime, y_name, y_path)
        else:
            print('y 已经有最新的，不用更新！')
            return old_data
    return new_data

if __name__ == '__main__':
    # res = check_input_x()
    res = check_input_y(list(pd.date_range(start='2018-01-31', end='2021-04-30', freq='M').strftime('%F')), 'CPI_当月同比')






